﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{
        await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml");
    }
    @{
        await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml");
    }
    <script src="/lib/xlsx/xlsx.full.min.js?v=@DateTime.Now.Ticks"></script>
    <link href="/css/YieldTriggerReport.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>YieldTriggerReport</title>
    <style type="text/css">
        /*报表样式*/
        html, body {
            background: url(../images/ProcessCapacity/bgwhite.png) no-repeat;
            background-size: cover;
            font-size: .16rem;
            position: relative;
            width: 100%;
            height: 100%;
            font-family: myFirstFont !important;
            color: black;
        }

        .hover-image {
            display: none;
            position: absolute;
            top: 20px;
            left: 0;
            width: 35vw;
            border: 1px solid #ccc;
            background: #fff;
            z-index: 999;
        }

        .warn-flag:hover .hover-image {
            display: block;
        }

        /*报表放大*/
        #maximizedreport {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            margin: 0;
            z-index: 1000;
            transition: all 0.3s;
            font-size: 1.5em !important;
            background-color: #f5f5f5;
        }

        #maximizedreport .note {
            font-size: 0.85em !important;
        }

        #maximizedreport #Tab1 {
            height: 90vh;
        }

        #maximizedreport #board #startdate,
        #maximizedreport #board #enddate {
            font-size: 0.85em !important;
            width: 12.5vw;
        }

        #maximizedreport #board select,
        #maximizedreport #board button,
        #maximizedreport #board .titleinput {
            font-size: 0.85em !important;
            width: 9vw;
        }

        #maximizedreport #tablereport {
            height: 90vh;
            font-size: 0.85em !important;
        }

        #maximizedreport #tablereport th {
            font-size: 1.45em !important;
        }

        #maximizedreport #reportdata th:first-child,
        #maximizedreport #reportdata td:first-child {
            left: 0px;
        }

        #maximizedreport #reportdata th:nth-child(2),
        #maximizedreport #reportdata td:nth-child(2) {
            left: 1.15rem;
        }

        #maximizedreport #reportdata th:nth-child(3),
        #maximizedreport #reportdata td:nth-child(3) {
            left: 2.7rem;
        }

        #maximizedreport #reportdata th:nth-child(4),
        #maximizedreport #reportdata td:nth-child(4) {
            left: 5rem;
        }

        #maximizedreport .popup {
            width: 80%;
        }

        #maximizedreport .popup span,
        #maximizedreport #defect_detail td {
            font-size: 0.85em !important;
        }

        #maximizedreport #defect_detail th {
            font-size: 1.5em !important;
        }

        .rightTop {
            background-color: #f7fdff;
        }

        .dropbtn, button {
            background-color: #0aa9cd;
        }

        #query > button {
            background-color: #0aa9cd;
            border: 2px solid #0aa9cd;
        }

        .dropdown-content {
            background-color: #12bed0;
        }

        .Zebra {
            background-color: #e5ecff;
        }

        .ZebraNo {
            background-color: #e8f1f9;
        }

        .ZebraTo {
            background-color: #ffffff;
        }

        .warn {
            background-color: #ffcccc;
        }

        .note {
            color: red;
            font-size: 0.15rem;
            font-weight: bolder;
        }

        .low {
            background-color: #ffff00;
            border-color: transparent;
        }

        .warning {
            /*
            background-color: #ffaf00;
            border-color: #ffaf00; 
            */
            background-color: #ffaf0078;
            border-color: transparent;
        }

        .danger {
            /*
            background-color: #ff1f00;
            border-color: #ff1f00;
            */
            background-color: #ff1f0078;
            border-color: transparent;
        }

        .jobnum:hover {
            background-color: #b3f1fe;
        }

        .truncate {
            /* max-width: 1.2rem; */
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            border-color: transparent;
        }

        td.percentage {
            border-color: transparent;
        }
        /*END*/

        #Tab1 {
            border: 1px solid #59ebe8;
            height: 9.3rem;
            background-image: url('../images/loading.gif');
            background-size: 0.8rem 0.8rem;
            background-repeat: no-repeat;
            background-position: center;
        }

        .popup {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 60%;
            background-color: white;
            box-shadow: 0 0 10px rgba(4, 193, 250,1);
            border-radius: 8px;
            z-index: 7;
        }

        .defect_close:hover {
            background-color: #d2e9f8;
        }

        #defect_detail > thead th {
            text-align: center;
            margin: auto;
            position: sticky;
            top: 0;
            background-color: #0bc4e9;
        }

        #defect_detail > thead > tr {
            height: 0.3rem;
            background-color: #0bc4e9;
        }

        .switch-container {
            display: flex;
            align-items: center;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 0.42rem;
            height: 0.24rem;
            top: 0.1rem;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: 0.4s;
            border-radius: 0.5rem;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 0.18rem;
            width: 0.18rem;
            left: 0.03rem;
            bottom: 0.028rem;
            background-color: white;
            transition: 0.4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: #4caf50;
        }

        input:checked + .slider:before {
            transform: translateX(0.18rem);
        }

        /*************************/
        #tablereport {
            float: left;
            width: 100%;
            font-size: 0.125rem;
            height: 100%;
            overflow-y: auto;
            /* position: relative; */
        }

        table {
            width: 100%;
            border-collapse: collapse;
            border: none;
            /*table-layout: fixed;*/
        }

        thead {
            text-align: center;
            margin: auto;
            top: 0;
            background-color: #a2c2e2;
        }

        thead > tr {
            font-size: 0.13rem;
            height: 0.5rem;
        }

        th, td {
            white-space: nowrap;
            padding: 0.05rem;
            border: none;
        }

        thead > tr {
            font-size: 0.13rem;
            height: 0.5rem;
        }

        #reportdata thead th {
            position: sticky;
            top: 0;
            background-color: #a2c2e2;
            z-index: 5;
        }

        /* 固定前四列 */
        #reportdata th:nth-child(-n+4) {
            position: sticky;
            z-index: 4;
            background-color: #a2c2e2;
        }

        #reportdata td:nth-child(-n+4) {
            position: sticky;
            z-index: 4;
            background-color: inherit;
        }

        /* 逐列调整 left 值，确保不被覆盖 */
        #reportdata th:first-child,
        #reportdata td:first-child {
            left: 0px;
        }

        #reportdata th:nth-child(2),
        #reportdata td:nth-child(2) {
            /*left: 0.84rem;*/
            left: calc(var(--col1-width, 0px));
        }

        #reportdata th:nth-child(3),
        #reportdata td:nth-child(3) {
            /*left: 1.95rem;*/
            left: calc(var(--col1-width, 0px) + var(--col2-width, 0px));
        }

        #reportdata th:nth-child(4),
        #reportdata td:nth-child(4) {
            /*left: 3.6rem;*/
            left: calc(var(--col1-width, 0px) + var(--col2-width, 0px) + var(--col3-width, 0px));
        }

        /* 确保表头的前四列有最高层级 */
        #reportdata th:nth-child(-n+4) {
            z-index: 6;
        }

        tfoot {
            font-size: 0.13rem;
            position: sticky;
            bottom: 0;
            background-color: #a2c2e2;
            height: 0.45rem;
        }

        tbody:hover .zebracro {
            background-color: #164362;
        }

    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden; color: black;">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="ProdExport('YieldTrigger')">@Label.Report@Label.Export</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border" id="report_id" ondblclick="maximizedreport()">
                    <div class="title note">
                        <span class="warn-flag" style="color:red; position: relative;">ℹ️<img src="../images/lot.png?v=@DateTime.Now.Ticks" class="hover-image" /></span>
                        @Label.Note_YieldTargetReport
                    </div>
                    <div id="board" class="chart">
                        <div class="query">
                            <span class="titleinput tle">@Label.Time:</span>
                            <input type="date" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time">
                            <span class="titleinput tle">@Label.To</span>
                            <input type="date" id="enddate" name="enddate" placeholder="@Label.Start@Label.End" style="margin-right: 0.1rem;">
                            <span class="titleinput tle">Project:</span>
                            <select id="cmb_proj_code" placeholder="select Project"></select>
                            <span class="titleinput tle">@Html.Raw(Label.Product):</span>
                            <select id="cmb_product_code" placeholder="select ProductCode"></select>
                            <span class="titleinput tle">@Html.Raw(Label.Process):</span>
                            <select id="cmb_process" placeholder="select Process" style="width: 1.9rem;"></select>
                            <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="Getdata()">@Label.Query</button>
                            <div style="float: right; line-height:0.5rem;"> 
                                <label class="switch">
                                    <input type="checkbox" id="rightSwitch" onclick="darkcolor()">
                                    <span class="slider"></span>
                                </label>
                            </div>
                        </div>
                        <div id="Tab1">
                            <div id="tablereport"></div>
                            <div class="popup">
                                <span class="defect_close" style="font-size:0.18rem;color:red; float:right;font-weight:bold;" onclick="funclose()">关闭×</span>
                                <div style="height:0.3rem">
                                    <span class="process_name" style="font-size:0.15rem;color:#007bff;font-weight:bold;line-height:0.3rem;padding-left: 0.15rem;"></span>
                                </div>
                                <div id="defect"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        $(".popup").css("display", "none");
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
            });

            function numberToUpperCase(number) {
                var uppercaseMonths = [
                    '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'
                ];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html('@Html.Raw(Label.Board_YieldTargetReport)');
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear();
                var myMonth = myDate.getMonth() + 1;
                var myToday = myDate.getDate();
                var myDay = myDate.getDay();
                var myHour = myDate.getHours();
                var myMinute = myDate.getMinutes();
                var mySecond = myDate.getSeconds();
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);
            // 设置全屏
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    // 判断浏览器设备类型
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {       //兼容火狐
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {    //兼容谷歌
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {        //兼容IE
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit + Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });
            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                endDate.setDate(endDate.getDate() - 1);
                var maxStartDate = endDate.toISOString().split('T')[0];
                $('#startdate').attr('max', maxStartDate);
                if (startDate > endDate) {
                    $('#startdate').val($(this).val());
                }
            });
        });

        //ComBoxYield
        var ComboxAction = function () {
            $.post(api + '/ReportAction/GetComBoxYieldTrigger', function (res) {
                let data = res.ReturnData;
                populateSelect("#cmb_proj_code", data.projcode, "NCCSAD");
                $("#cmb_proj_code").off("change").on("change", function () {
                    let projcode = $(this).val();
                    let filteredProducts = removeDuplicates(data.product.filter(p => p.projcode === projcode));
                    populateSelect("#cmb_product_code", filteredProducts, "ALL");
                    $("#cmb_product_code").trigger("change");
                });
                $("#cmb_product_code").off("change").on("change", function () {
                    let product = $(this).val();
                    let filteredProcesses = removeDuplicates(data.process.filter(p => p.product === product));
                    populateSelect("#cmb_process", filteredProcesses, "ALL");
                });
                $("#cmb_proj_code").val("NCCSAD").trigger("change");
            }, "json");
            function removeDuplicates(items) {
                let seen = new Set();
                return items
                    .filter(item => {
                        if (seen.has(item.value)) return false;
                        seen.add(item.value);
                        return true;
                    })
                    .sort((a, b) => a.text.localeCompare(b.text));
            }
            function populateSelect(selector, items, defaultValue = null) {
                $(selector).empty().append('<option value="ALL">ALL</option>');
                items.forEach(item => $(selector).append(`<option value="${item.value}">${item.text}</option>`));
                if (defaultValue && (defaultValue === "ALL" || items.some(item => item.value === defaultValue))) {
                    $(selector).val(defaultValue);
                }
            }
        };

        //定时查询
        var Tabtimer;
        function TabInterval() {
            clearInterval(Tabtimer);
            //每隔10m执行一次
            Tabtimer = setInterval(function () {
                var endDate = new Date($("#enddate").val());
                if (endDate > new Date()) {
                    getdate();
                }
            }, 10 * 60 * 1000);
        }

        $(function () {
            var startDate = new Date();
            startDate.setMonth(startDate.getMonth() - 1);
            startDate.setHours(0, 0, 0, 0);
            var endDate = new Date();
            endDate.setHours(0, 0, 0, 0);
            $('#startdate').val(startDate.toISOString().split('T')[0]);
            $('#enddate').val(endDate.toISOString().split('T')[0]);
            ComboxAction();
            setTimeout(function () {
                Getdata();
            }, 1500);
        })

        var Getdata = function () {
            getdate();
            TabInterval();
        }

        //报表导出
        var exporttype;
        var ProdExport = function (type) {
            exporttype = type;
            var formData = new FormData();
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('product_code', $("#cmb_product_code").val());
            formData.append('process_id', $("#cmb_process").val());
            formData.append('start', $('#startdate').val());
            formData.append('end', $('#enddate').val());
            formData.append('filename', type);
            var url = api + "/ReportAction/GetYieldTriggerReportToExcel";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }
        //POST 参数不固定 导出
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = exporttype.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }

        function loadingshow() {
            $('#btn_query').prop('disabled', true);
            $('#Tab1').css('background-image', 'url("../images/loading.gif")');
            $('#Tab1').css('background-size', '0.8rem 0.8rem');
            $('#Tab1').css('background-repeat', 'no-repeat');
            $('#Tab1').css('background-position', 'center');
        }
        function loadingnone() {
            $('#btn_query').prop('disabled', false);
            $('#Tab1').css('background-image', 'none');
        }
        function getExcelColor(percentage) {
            let red, green;
            if (percentage <= 65) {
                red = 255;
                green = Math.round((percentage / 65) * 255);
            } else if (percentage <= 90) {
                green = 255;
                red = Math.round(255 - ((percentage - 75) / 30) * 200);
            } else {
                green = Math.round(255 - ((percentage - 90) / 10) * 50);
                red = Math.round(55 - ((percentage - 90) / 10) * 25);
            }
            return `rgb(${red}, ${green}, 150)`;
        }

        //获取数据
        var Tab;
        var getdate = function () {
            let rightSwitch = document.getElementById("rightSwitch");
            rightSwitch.checked = false;
            $(".popup").css("display", "none");
            $("#tablereport").empty();
            var header_key = {
                start: $('#startdate').val(),
                end: $('#enddate').val()
            };
            var pam = {};
            pam.proj_code = $('#cmb_proj_code').val();
            pam.product_code = $('#cmb_product_code').val();
            pam.process_id = $('#cmb_process').val();
            pam.header_key = JSON.stringify(header_key);
            loadingshow();
            $.ajax({
                type: "POST",
                url: api + "/ReportAction/GetYieldTriggerReport",
                data: pam,
                dataType: "json",
                async: true,
                success: function (dt) {
                    loadingnone();
                    Tab = dt.ReturnData;
                    tablereport();
                }
            });
        }

        function updateColWidths(){
            const $table = $("#reportdata");
            const col1Width = $table.find("th:nth-child(1)").outerWidth();
            const col2Width = $table.find("th:nth-child(2)").outerWidth();
            const col3Width = $table.find("th:nth-child(3)").outerWidth();
            $(":root").css({
                "--col1-width": col1Width + "px",
                "--col2-width": col2Width + "px",
                "--col3-width": col3Width + "px"
            });
        }

        //合并相同行
        function mergeFunc(tableId, maxCol) {
            var tab = document.getElementById(tableId);
            //var maxCol = 3;
            //maxcol用于设置需要合并的列数
            var count, start;
            for (var col = maxCol - 1; col >= 0; col--) {
                //用于存储相同个数
                count = 1;
                for (var i = 0; i < tab.rows.length; i++) {
                    if (i > 0 && col > 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML
                        && tab.rows[i].cells[col - 1].innerHTML == tab.rows[i - 1].cells[col - 1].innerHTML) {
                        count++;
                    } else if (i > 0 && col == 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML) {
                        count++;
                    } else {
                        if (count > 1) {
                            start = i - count;
                            tab.rows[start].cells[col].rowSpan = count;
                            for (var j = start + 1; j < i; j++) {
                                tab.rows[j].removeChild(tab.rows[j].cells[col]);
                            }
                            count = 1;
                        }
                    }
                }
                if (count > 1) {
                    start = i - count;
                    tab.rows[start].cells[col].rowSpan = count;
                    for (var j = start + 1; j < i; j++) {
                        tab.rows[j].removeChild(tab.rows[j].cells[col]);
                    }
                }
            }
        }

        var tablereport = function () {
            $('#btn_query').prop('disabled', false);
            $("#tablereport").empty();
            var data = Tab.Table;
            data = data.map(item => {
                delete item.PRODUCT_SEQ;
                delete item.PROCESS_SEQ;
                return item;
            });
            var tester_end_html = `
            <table id="reportdata" class="DataSheet" border="1" style="width: 100%; height: 100%;">
                <thead><tr></tr></thead>
                <tbody id="report_tbody"></tbody>
            </table>`;
            $("#tablereport").append(tester_end_html);
            var aatest_table = $('#reportdata');
            var aatest_tbody = aatest_table.find('tbody');
            $("#reportdata>thead>tr, #report_tbody,#reportdata>tfoot>tr").empty();
            // 动态生成表头
            var aatest_headerRow = aatest_table.find('thead tr');
            var aatest_headers = Object.keys(data[0]);
            aatest_headers.forEach(function (header) {
                aatest_headerRow.append('<th>' + header + '</th>');
            });
            // 生成表格内容
            data.forEach((row, index) => {
                index++;
                let target = Number(row["YIELD_TARGET"]) || 0; 
                let newRow = $(`<tr class="${(index % 2) ? "ZebraNo" : "ZebraTo"}"></tr>`);
                aatest_headers.forEach((header) => {
                    let tdvalue = row[header];
                    let background = "";
                    let clickHandler = `defect_detail('${row['PROJ_CODE']}','${row['PRODUCT_CODE']}','${row['PROCESS_ID']}','${header}')`;
                    if (["PROJ_CODE", "PRODUCT_CODE", "PROCESS_ID"].includes(header)) {
                        newRow.append(`<td class="truncate">${tdvalue}</td>`);
                        return;
                    }
                    if (header === "YIELD_TARGET" && !isNaN(tdvalue)) {
                        tdvalue = `${parseFloat(tdvalue).toFixed(2)}%`;
                        newRow.append(`<td class="truncate">${tdvalue}</td>`);
                        return;
                    }
                    if (tdvalue == null || tdvalue === "NULL") {
                        tdvalue = "No Data";
                        background = "percentage";
                    } else {
                        let yieldvalue = Number(tdvalue) || 0;
                        tdvalue = `${isNaN(tdvalue) ? tdvalue : tdvalue.toFixed(2)+"%"}`;
                        //background = (yieldvalue >= target ? "percentage" :(yieldvalue >= target * 0.95 ? "warning" :"danger"));
                        var diff = (target - yieldvalue);
                        //console.log(`${target} - ${yieldvalue}=${diff}`);
                        if (diff > 0 && diff < 3) {
                            background = "low";
                        } else if (diff >= 3 && diff < 5) {
                            background = "warning";
                        } else if (diff >= 5) {
                            background = "danger";
                        } else {
                            background = "percentage";
                        }
                    }
                    newRow.append(`<td class="${background}" onclick="${clickHandler}">${tdvalue}</td>`);
                });
                aatest_tbody.append(newRow);
            });
            updateColWidths();
            //mergeFunc("reportdata", 2);
        }

        function darkcolor() {
            let rightSwitch = document.getElementById("rightSwitch");
            $('.percentage').each(function () {
                const percentage = parseInt($(this).text().replace('%', ''), 10);
                var color = rightSwitch.checked ? getExcelColor(percentage) : "transparent";
                $(this).css('background-color', color);
            })
        }

        function funclose() {
            $(".popup").css("display", "none");
            $("#defect").empty();
        }

        //sn_defect
        var details;
        function defect_detail(projcode, product, process_id, header) {
            $(".popup").css("display", "none");
            $(".process_name").text(`工序：${process_id}`);
            $("#defect").empty();
            var data = Tab.Table1
                .filter(item => item.PROJ_CODE == projcode && item.PRODUCT_CODE == product && item.PROCESS_ID === process_id && item.DATE === header)
                .map(item => {
                    let newItem = Object.assign({}, item);
                    delete newItem.ALL_FAIL_QTY;
                    delete newItem.DATE;
                    return newItem;
                });
            var create_table_detail = function (data) {
                $(".popup").css("display", "block");
                var table_header = "", table_tbody = "";
                var headers = Object.keys(data[0]);
                headers.forEach(function (header) {
                    table_header += `<th>${header}</th>`;
                });
                var braTo = "style='text-align:center;background-color:#ffffff;'";
                var braNo = "style='text-align:center;background-color:#d2e9f8;'";
                data.forEach(function (row, index) {
                    index++;
                    var style = (index % 2) > 0 ? braNo : braTo;
                    var newRow = "<tr>";
                    headers.forEach(function (header) {
                        var cellData = row[header];
                        if (header.includes("YIELD")) {
                            cellData = !isNaN(parseFloat(cellData)) ? `${parseFloat(cellData).toFixed(2)}%` : "N/A";
                        }
                        newRow += `<td ${style} class="truncate">${cellData}</td>`;
                    });
                    newRow += "</tr>";
                    table_tbody += newRow;
                });
                var defect_table_html = `
                <table id="defect_detail" style="margin: 0rem 0.15rem 0.15rem 0.15rem;width: calc(100% - 0.3rem);">
                    <thead><tr>${table_header}</tr></thead>
                    <tbody>${table_tbody}</tbody>
                </table>`;
                $("#defect").append(defect_table_html);
            };
            if (data.length > 0) {
                var header_key = {
                    year: new Date($('#enddate').val()).getFullYear(),
                    date: header
                };
                var pam = {};
                pam.proj_code = projcode;
                pam.product_code = product;
                pam.process_id = process_id;
                pam.header_key = JSON.stringify(header_key);
                $.ajax({
                    type: "POST",
                    url: api + "/ReportAction/GetYieldDefectDetails",
                    data: pam,
                    dataType: "json",
                    async: false,
                    success: function (dt) {
                        $("#defect").empty();
                        create_table_detail(data);
                        details = dt.ReturnData.Table.map(item => {
                            delete item.PROJ_CODE;
                            delete item.PRODUCT_CODE;
                            return item;
                        });
                        if(details.length > 0)
                        {
                            $("#defect").append(`<span class="process_name" style="font-size:0.15rem;color:#007bff;font-weight:bold;line-height:0.3rem;padding-left: 0.15rem;">Defect Details</span>`);
                            $("#defect").append(`<span style="float: right; font-size:0.15rem;color:#007bff;font-weight:bold;line-height:0.3rem;padding-right: 0.15rem;"onclick="exportDefect('${process_id}')">导出</span>`);
                            create_table_detail(details);
                        }
                        if (details.length > 23) {
                            $("#defect").css("height", "7rem");
                            $("#defect").css("overflow-y", "auto");
                        } else {
                            $("#defect").css("height", "50%");
                        }
                    }
                });
            }
        }

        var exportDefect = function(process){
            const book = XLSX.utils.book_new();
            const sheet = XLSX.utils.json_to_sheet(details);
            XLSX.utils.book_append_sheet(book, sheet);
            XLSX.writeFile(book,`${process}.xlsx`);
        }

        var maximized = false;
        function toggleMaximize(elementId, maximizedId, chartId) {
            const tab = document.getElementById(elementId) || document.getElementById(maximizedId);
            if (tab) {
                if (tab.id === elementId) {
                    maximized = true;
                    tab.id = maximizedId;
                    if (chartId) maxchart(chartId);
                } else {
                    maximized = false;
                    tab.id = elementId;
                    if (chartId) minchart(chartId);
                }
            }
        }
        function maximizedreport() {
            toggleMaximize("report_id", "maximizedreport");
            updateColWidths();
        }
    </script>
</body>
</html>
